package com.teacher.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.teacher.common.CommonResult;
import com.teacher.mapper.TermMapper;
import com.teacher.pojo.entity.StaticData;
import com.teacher.mapper.StaticDataMapper;
import com.teacher.pojo.entity.StuClass;
import com.teacher.pojo.vo.all.ClassLevelGetVo;
import com.teacher.service.IAllService;
import com.teacher.service.IStaticDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.teacher.service.IStuClassService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 静态数据 服务实现类
 * </p>
 *
 * @author zfm
 * @since 2021-08-29
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class StaticDataServiceImpl extends ServiceImpl<StaticDataMapper, StaticData> implements IStaticDataService {

    @Autowired
    private TermMapper termMapper;

    @Autowired
    private IStuClassService iStuClassService;

    @Autowired
    private IAllService iAllService;

    /**
     * 生成本学期数据
     *
     * @return
     */
    @Override
    @Async
    public void create() {
        Long termId = termMapper.getCurrentTerm();

        // 先删除旧数据
        this.remove(new QueryWrapper<StaticData>().lambda()
                .eq(StaticData::getTermId, termId));

        List<StuClass> stuClass = iStuClassService.list(new QueryWrapper<StuClass>().lambda()
                .eq(StuClass::getStatus, 10));
        List<StaticData> staticDataList = new ArrayList<>();
        for (StuClass aClass : stuClass) {
            List<ClassLevelGetVo> voList = iAllService.getLevelByClassId(aClass.getId()).getData();
            if (voList == null) {
                continue;
            }
            for (ClassLevelGetVo classLevelGetVo : voList) {
                StaticData staticData = new StaticData();
                BeanUtils.copyProperties(classLevelGetVo, staticData);
                staticData.setClassName(aClass.getClassName());
                staticData.setTermId(termId);
                staticData.setClassId(aClass.getId());
                staticDataList.add(staticData);
            }
        }
        this.saveBatch(staticDataList);
    }
}
